use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::net::UdpSocket;
use tokio::time::interval;

use crate::tasks::AsyncTask;

pub struct UdpTimeTask {
    server_addr: String,
    interval_secs: u64,
}

impl UdpTimeTask {
    pub fn new(server_addr: impl Into<String>, interval_secs: u64) -> Self {
        Self {
            server_addr: server_addr.into(),
            interval_secs,
        }
    }
}

impl AsyncTask for UdpTimeTask {
    fn start(
        self,
        stop_rx: tokio::sync::watch::Receiver<bool>,
    ) -> tokio::task::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>> {
        tokio::spawn(async move {
            // 创建UDP socket
            let socket = UdpSocket::bind("0.0.0.0:0").await?;

            // 创建定时器，按指定间隔触发
            let mut interval = interval(Duration::from_secs(self.interval_secs));

            loop {
                // 检查是否收到停止信号
                if *stop_rx.borrow() {
                    break;
                }

                // 等待下一个间隔
                interval.tick().await;

                // 获取当前时间
                let now = SystemTime::now();
                let timestamp = now
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or(Duration::from_secs(0))
                    .as_secs();

                // 发送时间到UDP服务器
                let time_str = format!("Current time: {}", timestamp);
                let _ = socket.send_to(time_str.as_bytes(), &self.server_addr).await;
            }

            Ok(())
        })
    }
}
